package com.hisense.ovcloud.common3.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.session.data.redis.config.ConfigureRedisAction;

@Configuration
@Slf4j
@Lazy
@ConditionalOnClass(ConfigureRedisAction.class)
public class LettuceConfig {
//    @Value("${spring.data.redis.commandTimeoutSecond:5}")
//    private int commandTimeout;
//
//    @Value("${spring.data.redis.refreshTriggersTimeoutSecond:10}")
//    private int refreshTriggersTimeoutSecond;
//
//    @Value("${spring.data.redis.periodicRefreshSecond:10}")
//    private int periodicRefreshSecond;
//
//    @Value("${spring.data.redis.lettuce.pool.testOnBorrow:true}")
//    private boolean testOnBorrow;
//
//    @Value("${spring.data.redis.lettuce.pool.enableAllAdaptiveRefreshTriggers:true}")
//    private boolean enableAllAdaptiveRefreshTriggers;
//
//    @Value("${spring.data.redis.lettuce.pool.validateConnection:false}")
//    private boolean validateConnection;
//
//    @Value("${spring.data.redis.lettuce.pool.testOnCreate:true}")
//    private boolean testOnCreate;
//
//    @Value("${spring.data.redis.lettuce.pool.testOnReturn:false}")
//    private boolean testOnReturn;
//
//    @Value("${spring.data.redis.lettuce.pool.setShareNativeConnection:true}")
//    private boolean setShareNativeConnection;
//
//    @Value("${spring.data.redis.lettuce.pool.resetConnection:false}")
//    private boolean resetConnection;
//
//    private final RedisProperties redisProperties;
//
//    public LettuceConfig(RedisProperties redisProperties) {
//        this.redisProperties = redisProperties;
//    }
//
//    @Bean
//    @SuppressWarnings("all")
//    public GenericObjectPoolConfig<?> genericObjectPoolConfig(RedisProperties.Pool properties) {
//        GenericObjectPoolConfig<?> config = new GenericObjectPoolConfig<>();
//        config.setMaxTotal(properties.getMaxActive());
//        config.setMaxIdle(properties.getMaxIdle());
//        config.setMinIdle(properties.getMinIdle());
//        if (null != properties.getTimeBetweenEvictionRuns()) {
//            config.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRuns().toMillis());
//        }
//        if (null != properties.getMaxWait()) {
//            config.setMaxWaitMillis(properties.getMaxWait().toMillis());
//        }
//        config.setTestOnBorrow(testOnBorrow);
//        config.setTestOnCreate(testOnCreate);
//        config.setTestOnReturn(testOnReturn);
//        return config;
//    }
//
//    @Bean(destroyMethod = "destroy")
//    public LettuceConnectionFactory lettuceConnectionFactory() {
//        //开启 自适应集群拓扑刷新和周期拓扑刷新
//        ClusterTopologyRefreshOptions clusterTopologyRefreshOptions = ClusterTopologyRefreshOptions.builder()
//                // 开启全部自适应刷新
//                .enableAllAdaptiveRefreshTriggers() // 开启自适应刷新,自适应刷新不开启,Redis集群变更时将会导致连接异常
//                // 自适应刷新超时时间(默认30秒)
//                .adaptiveRefreshTriggersTimeout(Duration.ofSeconds(refreshTriggersTimeoutSecond)) //默认关闭开启后时间为30秒
//                // 开周期刷新
//                .enablePeriodicRefresh(Duration.ofSeconds(periodicRefreshSecond))  // 默认关闭开启后时间为60秒 ClusterTopologyRefreshOptions.DEFAULT_REFRESH_PERIOD 60  .enablePeriodicRefresh(Duration.ofSeconds(2)) = .enablePeriodicRefresh().refreshPeriod(Duration.ofSeconds(2))
//                .build();
//
//        ClientOptions clientOptions = enableAllAdaptiveRefreshTriggers ? ClusterClientOptions.builder()
//                .topologyRefreshOptions(clusterTopologyRefreshOptions)
//                .build() : ClusterClientOptions.builder()
//                .build();
//
//        LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
//                .poolConfig(genericObjectPoolConfig(redisProperties.getLettuce().getPool()))
//                //.readFrom(ReadFrom.MASTER_PREFERRED)
//                .clientOptions(clientOptions)
//                .commandTimeout(Duration.ofSeconds(commandTimeout)) //默认RedisURI.DEFAULT_TIMEOUT 60
//                .build();
//
//        List<String> clusterNodes = new ArrayList<>();
//        try{
//            clusterNodes = redisProperties.getCluster().getNodes();
//        }catch (Exception e){
//            log.info("didn't fetch redis cluster node, use default instead.");
//        }
//        Set<RedisNode> nodes = new HashSet<>();
//        clusterNodes.forEach(address -> nodes.add(new RedisNode(address.split(":")[0].trim(), Integer.parseInt(address.split(":")[1]))));
//
//        RedisClusterConfiguration clusterConfiguration = new RedisClusterConfiguration();
//        clusterConfiguration.setClusterNodes(nodes);
//        clusterConfiguration.setPassword(RedisPassword.of(redisProperties.getPassword()));
//        clusterConfiguration.setMaxRedirects(redisProperties.getCluster().getMaxRedirects());
//
//        LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(clusterConfiguration, clientConfig);
//        lettuceConnectionFactory.setValidateConnection(validateConnection);
//        lettuceConnectionFactory.setShareNativeConnection(setShareNativeConnection); //是否允许多个线程操作共用同一个缓存连接，默认true，false时每个操作都将开辟新的连接
//        if(resetConnection){
//            lettuceConnectionFactory.resetConnection(); // 重置底层共享连接, 在接下来的访问时初始化
//        }
//        return lettuceConnectionFactory;
//    }

    @Bean("stringReactiveRedisTemplate")
    public ReactiveRedisTemplate<String, String> stringReactiveRedisTemplate(ReactiveRedisConnectionFactory factory) {
        StringRedisSerializer stringSerializer = new StringRedisSerializer();
        RedisSerializationContext<String, String> context = RedisSerializationContext.<String, String>newSerializationContext()
                .key(stringSerializer)
                .value(stringSerializer)
                .hashKey(stringSerializer)
                .hashValue(stringSerializer)
                .build();
        return new ReactiveRedisTemplate<>(factory, context);
    }
}
